package com.example.forum.Controller;
/* @Author      zouzh
 * @PackageName forum
 * @Package     com.example.forum.Controller
 * @Date        2023/9/18 16:04
 */

import com.example.forum.common.AppConfig;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.service.IArticleService;
import com.example.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IBoardService boardService;

    @ApiOperation("/发布新帖")
    @PostMapping("/create")
    public AppResult craete( HttpServletRequest request,
                            @ApiParam("板块ID") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content){
        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 版块的校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() ==1 || board.getState() == 1){
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        // 封装文章对象
        Article article = new Article();
        article.setUserId(user.getId()); // 作者Id
        article.setTitle(title);         // 标题
        article.setContent(content);     // 正文
        article.setBoardId(boardId);     // 版块Id

        // 调用 service
        articleService.creat(article);
        // 成功返回
        return AppResult.success();

    }

    @ApiOperation("根据 帖子ID 查询帖子详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request, @ApiParam("帖子 id") @RequestParam("id") @NonNull Long id){
        // 获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调用 service
        Article article = articleService.selectDetailById(id);
        // 返回结果
        if (article == null || article.getDeleteState() == 1){
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 当前用户是否作者
        if (article.getUserId() == user.getId()){
            // 标识为作者
            article.setOwn(true);
        }
        return AppResult.success(article);
    }
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId (@ApiParam("板块 id ") @RequestParam(value = "boardId", required = false) Long boardId){

        List<Article> articles;

        if (boardId == null) {
            // 如果传入参数为空 查询所有结果
            articles = articleService.selectAll();
        }else {
            // 如果参数不为空，则根据板块 id 查询结果集
            articles = articleService.selectAllByBoardId(boardId);
        }
        // 结果集是否为空
        if (articles == null){
        //   如果 结果集为空 则设置为空列表
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify( HttpServletRequest request,
                            @ApiParam("帖子 id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content){

        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 检验用户状态
        if (user.getState() == 1){
            // 返回错误描述
            return  AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null){
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 判断用户是不是作者
        if (user.getId() != article.getUserId()){
            // 打印日志
            log.info(ResultCode.FAILED_UNAUTHORIZED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
        }
        // 判断帖子的状态
        if (article.getState() == 1 || article.getDeleteState() == 1 ){
            // 打印日志
            log.info(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 调用 service

        articleService.modify(id, title, content);
        // 打印日志
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");

        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
            @ApiParam("帖子 id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 用户是否被禁言
        if (user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 调用Service
        articleService.thumbsUp(id);
        // 返回结果
        return AppResult.success();

    }
    @ApiOperation("删除帖子")
    @PostMapping("/delete")

    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        // 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            // 表示用户已禁言
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        // 查询帖子
        Article article = articleService.selectById(id);
        // 帖子状态
        if (article == null || article.getDeleteState() == 1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 用户是否为作者
        if (user.getId() != article.getUserId()){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }
        // 调用 service
        articleService.deleteById(id);
        // 返回成功结果
        return AppResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户 id") @RequestParam(value = "userId", required = false) Long userId){
        List<Article> articles;
        // 如果 userId 为空，那么从 session 中获取当前登录用户的 id
        if (userId == null) {
            HttpSession session = request.getSession(false);
             User user= (User) session.getAttribute(AppConfig.USER_SESSION);
             userId = user.getId();
        }
        // 调用 service
        articles = articleService.selectByUserId(userId);
        // 结果集是否为空
        if (articles == null){
            //   如果 结果集为空 则设置为空列表
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }


}
